package com.demo.auth.config;

import com.demo.auth.filter.JWTLoginFilter;
import com.demo.auth.service.remote.DispatchRemoteAuthUserMenuService;
import com.demo.auth.service.security.CustomAuthenticationProvider;
import com.sudo.demo.security.config.WebSecurityConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;

/**
 * SpringSecurity的配置
 * 通过SpringSecurity的配置，将JWTLoginFilter，JWTAuthenticationFilter组合在一起
 *
 * @author zhaoxinguo on 2017/9/13.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class AuthWebSecurityConfig extends WebSecurityConfig {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Resource
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Resource
    private DispatchRemoteAuthUserMenuService dispatchRemoteAuthUserMenuService;

    // 设置 HTTP 验证规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.addFilter(new JWTLoginFilter(authenticationManager()));
        http.formLogin()
                .loginProcessingUrl("/login")   //默认登录地址/login
                .successHandler(authenticationSuccessHandler)// 认证成功处理器
                .failureHandler(authenticationFailureHandler);// 认证失败处理器
        http.logout() // 默认注销行为为logout，可以通过下面的方式来修改
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login") //设置注销成功后跳转页面，默认是跳转到登录页面
                .permitAll();
    }

    // 该方法是登录的时候会进入
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义身份验证组件
        auth.authenticationProvider(
                new CustomAuthenticationProvider(userDetailsService, bCryptPasswordEncoder,dispatchRemoteAuthUserMenuService)
        );
    }

}
